/*
 * Copyright 2010 Yaroslav Klymko aka t3hnar
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package ua.t3hnar.io.serializer;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import ua.t3hnar.io.serializer.handlers.FieldHandler;
import ua.t3hnar.io.serializer.handlers.ToStreamException;

import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Field;

/**
 * @author Yaroslav Klymko aka t3hnar
 */
class StreamConnector extends StreamWorker<OutputStream> {
// ------------------------------ FIELDS ------------------------------

    private static final Log LOG = LogFactory.getLog(StreamConnector.class);

// --------------------------- CONSTRUCTORS ---------------------------

    StreamConnector(final SerializableFieldOwner owner, final Field field, final FieldHandler handler) {
        super(owner, field, handler);
    }

// -------------------------- OTHER METHODS --------------------------

    @Override
    void work(final OutputStream param) throws StreamSerializationException {
        LOG.debug("Working; param: " + param);
        if (param == null) {
            throw new IllegalArgumentException("Param is null");
        }

        final InputStream inputStream = getStream(getOwner(), getField(), getHandler());
        connect(param, inputStream);
    }

    void connect(final OutputStream outputStream, final InputStream inputStream) throws StreamSerializationException {
        LOG.debug("Connecting stream; outputStream: " + outputStream);
        if (outputStream == null) {
            throw new IllegalArgumentException("OutputStream is null");
        }

        final byte[] buffer;
        if (inputStream != null) {
            try {
                buffer = IOUtils.toByteArray(inputStream);
            } catch (IOException e) {
                final String message = "Failed to read stream: " + e;
                LOG.debug(message);
                throw new StreamSerializationException(message, e);
            }
        } else {
            buffer = new byte[0];
        }

        try {
            final DataOutputStream dataOutputStream = new DataOutputStream(outputStream);
            dataOutputStream.writeInt(buffer.length);
            IOUtils.write(buffer, dataOutputStream);
        } catch (IOException e) {
            final String message = "Failed to write stream: " + e;
            LOG.debug(message);
            throw new StreamSerializationException(message, e);
        }
    }

    InputStream getStream(final SerializableFieldOwner owner, final Field field, final FieldHandler<?> handler) throws StreamSerializationException {
        LOG.debug("Retrieving stream; owner: " + owner + "; field: " + field + "; handler: " + handler);
        if (owner == null || field == null || handler == null) {
            throw new IllegalArgumentException("One of the parameters is null");
        }

        final Object instance;
        try {
            instance = getInstance(owner, field);
        } catch (IllegalAccessException e) {
            final String message = "Failed to access instance field: " + e;
            LOG.debug(message);
            throw new StreamSerializationException(message, e);
        }

        if (instance == null) {
            return null;
        }

        try {
            return handler.toStream(instance);
        } catch (ToStreamException e) {
            final String message = "Failed to retrieve stream: " + e;
            LOG.debug(message);
            throw new StreamSerializationException(message, e);
        }
    }

    Object getInstance(final SerializableFieldOwner owner, final Field field) throws IllegalAccessException {
        LOG.debug("Retrieving instance; owner: " + owner + "; field: " + field);
        if (owner == null || field == null) {
            throw new IllegalArgumentException("One of the parameters is null");
        }

        final boolean accessible = field.isAccessible();
        field.setAccessible(true);
        try {
            return field.get(owner);
        }
        finally {
            field.setAccessible(accessible);
        }
    }
}
